﻿using InTheHand.Net;
using MyTRCP.Common.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace MyTRCP.Client
{
    /// <summary>
    /// ScanBTWindow.xaml 的交互逻辑
    /// </summary>
    public partial class ScanBTWindow : Window
    {
        private readonly List<BtDevInfo> _devList;
        private readonly Func<Task<IReadOnlyCollection<BtDevInfo>?>> _scanFunc;
        public BluetoothAddress? SelectedMac { get; private set; }
        public ScanBTWindow(Func<Task<IReadOnlyCollection<BtDevInfo>?>> scanFunc)
        {
            InitializeComponent();
            _devList = new List<BtDevInfo>();
            _scanFunc = scanFunc;
            lb_devs.ItemsSource = _devList;
        }

        private void b_ok_Click(object sender, RoutedEventArgs e)
        {
            if (lb_devs.SelectedItem != null && lb_devs.SelectedItem is BtDevInfo ba)
            {
                SelectedMac = new BluetoothAddress(ba.MacAddress);
                DialogResult = true;
                Close();
            }
            else
            {
                MessageBox.Show("请选择一个地址进行添加");
            }
        }

        private void b_cancel_Click(object sender, RoutedEventArgs e)
        {
            SelectedMac = null;
            DialogResult = false;
            Close();
        }


        private void ListBoxItem_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            b_ok_Click(sender, e);
        }

        private async void b_scan_Click(object sender, RoutedEventArgs e)
        {
            b_scan.IsEnabled = false;
            object oriTips = b_scan.Content;
            b_scan.Content = "扫描中...";
            var result = await _scanFunc();
            if (result != null)
            {
                lb_devs.ItemsSource = null;
                _devList.Clear();
                _devList.AddRange(result);
                lb_devs.ItemsSource = _devList;
            }
            else
            {
                MessageBox.Show("未搜索到目标设备");
            }
            b_scan.IsEnabled = true;
            b_scan.Content = oriTips;
        }
    }
}
